<template>
  <div class="app-container">
    <div class="filter-container" v-if="false">
      <el-input
        v-model="listQuery.id"
        placeholder="ID"
        style="width: 200px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.user_id"
        placeholder="会员ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-button
        v-waves
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        style="margin-left: 10px;"
        @click="handleFilter"
      >搜 索</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-refresh"
        class="filter-item"
        style="margin-left: 10px;"
        @click="clearFilter"
      >清除筛选</el-button>
    </div>
    <div class="filter-container" v-if="false">
      <el-button
        v-waves
        type="success"
        icon="el-icon-download"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleExport"
      >导出 Excel</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column sortable="custom" prop="id" label="ID" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户ID">
        <template slot-scope="{row}">
          <span v-if="row.user">{{ row.user.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称">
        <template slot-scope="{row}">
          <span v-if="row.user">{{ row.user.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话">
        <template slot-scope="{row}">
          <span v-if="row.user">{{ row.user.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="{row}">
          <span>{{ row.status | statusText }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" sortable="custom" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="220"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleClick(row)">
            操作
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'

const initQuery = {
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '+id'
}

export default {
  name: 'UserBalance',
  components: {
    Pagination
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    changeText(v) {
      return +v > 0 ? `+${+v}` : `${+v}`
    },
    orderText(v) {
      return +v > 0 ? +v : ''
    },
    statusText(v) {
      if (+v === 1) {
        return '已审核'
      }
      return '待审核'
    }
  },
  data() {
    return {
      listLoading: false,
      list: [],
      listQuery: {},
      defaultSort: {}
    }
  },
  created() {
    this.parseQuery()
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleClick(row) {
      if (row.user) {
        this.$router.push(`/member/list?id=${row.user.id}`)
      }
    },
    /**
     * 获取数据列表
     */
    getList() {
      this.listLoading = true
      api.member.getAreaReg({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
        this.listLoading = false
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 刷新
     */
    refresh() {
      this.$router.push({
        path: '/member/reg-area',
        query: this.listQuery
      })
    },
    /**
     * 过滤(筛选)
     */
    handleFilter() {
      // this.listQuery.page = 1
      this.refresh()
    },
    /**
     * 清除筛选
     */
    clearFilter() {
      this.listQuery = Object.assign({}, initQuery)
      this.defaultSort = {}
      this.refresh()
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
      // user id
      const user_id = +this.$route.params.id || 0
      console.log(user_id)
      this.listQuery.user_id = user_id
    },
    /**
     * 排序
     * @param data
     */
    sortChange(data) {
      const sortBy = (prop, order) => {
        if (prop && order === 'ascending') {
          this.listQuery.sort = `+${prop}`
        } else if (prop && order === 'descending') {
          this.listQuery.sort = `-${prop}`
        } else {
          this.listQuery.sort = ''
        }
      }
      const { prop, order } = data
      sortBy(prop, order)
      this.handleFilter()
    },
    /**
     * 导出
     */
    async handleExport() {
      // const formatJson = (filterVal, jsonData) => {
      //   return jsonData.map(v => filterVal.map(j => {
      //     if (j === 'change') {
      //       return this.$options.filters['changeText'](v[j])
      //     }
      //     if (j === 'order_id') {
      //       return this.$options.filters['orderText'](v[j])
      //     }
      //     return v[j]
      //   }))
      // }
      // this.listLoading = true
      // const response = await api.member.getStoreList({ ...this.listQuery, export: true })
      // import('@/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['ID', '会员ID', '之前数量', '改变', '现在数量', '操作', '订单ID', '时间']
      //   const filterVal = ['id', 'user_id', 'num', 'change', 'result', 'text', 'order_id', 'create_time']
      //   const list = response.data
      //   const data = formatJson(filterVal, list)
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data,
      //     filename: '云仓明细列表'
      //   })
      // })
      // this.listLoading = false
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>
